package com.sskj.mine.asset;

import android.content.Context;
import android.content.Intent;
import android.media.Image;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.hey.lib.HeySpinner;
import com.sskj.common.base.App;
import com.sskj.common.rxbus2.RxBus;
import com.sskj.common.rxbus2.Subscribe;
import com.sskj.common.rxbus2.ThreadMode;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.DisposUtil;
import com.sskj.common.util.SPUtil;
import com.sskj.common.util.TimeUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.SPConfig;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.mine.R;
import com.sskj.mine.R2;
import com.sskj.mine.asset.data.AddressBean;
import com.sskj.mine.asset.data.RechargeTypeBean;
import com.sskj.mine.asset.data.WithdrawConfigBean;
import com.sskj.mine.component.DaggerUserDataComponent;

import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Flowable;
import io.reactivex.disposables.Disposable;

/**
 * @author Hey
 * Create at  2019/05/04
 */
public class WithdrawActivity extends BaseActivity<WithdrawPresenter> {


    @BindView(R2.id.right_tv)
    TextView rightTv;
    @BindView(R2.id.select_coin)
    HeySpinner selectCoin;
    @BindView(R2.id.available_tv)
    TextView availableTv;
    @BindView(R2.id.address_edt)
    EditText addressEdt;
    @BindView(R2.id.num_edt)
    EditText numEdt;
    @BindView(R2.id.unit_tv)
    TextView unitTv;
    @BindView(R2.id.max_num_tv)
    TextView maxNumTv;
    @BindView(R2.id.password_edt)
    EditText passwordEdt;
    @BindView(R2.id.code_edt)
    EditText codeEdt;
    @BindView(R2.id.get_code_tv)
    TextView getCodeTv;
    @BindView(R2.id.address_img)
    ImageView addressImg;
    @BindView(R2.id.submit_btn)
    Button submitBtn;
    private Disposable typeDispo;
    private String pid;
    private String coinType;
    @Inject
    UserViewModel userViewModel;
    private UserData userData;
    private Disposable timeDis;

    @Override
    public int getLayoutId() {
        return R.layout.mine_activity_withdraw;
    }

    @Override
    public WithdrawPresenter getPresenter() {
        return new WithdrawPresenter();
    }

    @Override
    public void initView() {
        setTitle(getString(R.string.mine_withdrawActivity1));
        RxBus.getDefault().register(this);
        DaggerUserDataComponent.create().inject(this);
        selectCoin.setItemGravity(Gravity.CENTER);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
            } else {
                userData = null;
            }
            availableTv.setText(String.format("%s USDT", ""));

        });
        rightTv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.mipmap.mine_icon_history, 0);
        rightTv.setVisibility(View.VISIBLE);
    }

    @Override
    public void initData() {
        mPresenter.getType();
    }

    @Override
    protected void initEvent() {
        ClickUtil.click(rightTv, () -> ARouter.getInstance().build(RConfig.MINE_ASSET_RECORDS).withInt(Constans.TYPE, 0).navigation());

        ClickUtil.click(addressImg, () -> AddressListActivity.start(this));
        ClickUtil.click(getCodeTv, () -> {
            getCodeTv.setEnabled(false);
            String account = SPUtil.get(SPConfig.MOBILE, "");
            mPresenter.sendSms(account);
        });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateAddress(AddressBean addressBean) {
        if (addressEdt != null) {
            addressEdt.setText(addressBean.getAddress());
        }
    }

    public static void start(Context context) {
        Intent intent = new Intent(context, WithdrawActivity.class);
        context.startActivity(intent);
    }

    public void updateType(List<RechargeTypeBean> data) {
        if (data == null || data.size() <= 0) {
            return;
        }
        pid = data.get(0).getPid();
        coinType = data.get(0).getCoin_type();
        refresh();
        typeDispo = Flowable.fromIterable(data)
                .map(RechargeTypeBean::getPname)
                .toList()
                .subscribe((strings, throwable) -> {
                    selectCoin.attachData(strings);
                    selectCoin.setOnSelectListener(position -> {
                        pid = data.get(position).getPid();
                        coinType = data.get(position).getCoin_type();
                        refresh();
                    });

                });
    }

    private void refresh() {
        mPresenter.getWithdrawConfig(pid);
    }

    public void updateUI(WithdrawConfigBean data) {
        maxNumTv.setText(data.getTb_max());
        numEdt.setHint(String.format(getString(R.string.mine_withdrawActivity2), data.getTb_min()));
        availableTv.setText(data.getUser_usable());
        ClickUtil.click(submitBtn, () -> {
            if (checkParam()) {
                String account = SPUtil.get(SPConfig.ACCOUNT, "");
                mPresenter.withdraw(numEdt.getText().toString()
                        , pid, passwordEdt.getText().toString(),
                        codeEdt.getText().toString(),
                        account, addressEdt.getText().toString()
                );
            }
        });
    }

    private boolean checkParam() {

        if (TextUtils.isEmpty(addressEdt.getText())) {
            ToastUtil.showShort(getString(R.string.mine_addAddressActivity2));
            return false;
        }
        if (TextUtils.isEmpty(numEdt.getText())) {
            ToastUtil.showShort(getString(R.string.mine_withdrawActivity4));
            return false;
        }
        if (TextUtils.isEmpty(codeEdt.getText())) {
            ToastUtil.showShort(getString(R.string.mine_withdrawActivity5));
            return false;
        }
        if (TextUtils.isEmpty(passwordEdt.getText())) {
            ToastUtil.showShort(getString(R.string.mine_transferActivity4));
            return false;
        }
        return true;
    }

    public void sendCheckCodeSuccess() {
        DisposUtil.close(timeDis);
        timeDis = TimeUtil.newTime(this)
                .subscribe(aLong -> {
                    if (aLong > 0) {
                        getCodeTv.setText(aLong + "s");
                    } else {
                        getCodeTv.setText(getString(R.string.mine_withdrawActivity7));
                        getCodeTv.setEnabled(true);
                    }
                });
    }

    @Override
    protected void onDestroy() {
        DisposUtil.close(timeDis);
        super.onDestroy();
    }

    public void sendCheckCodeFail() {
        getCodeTv.setEnabled(true);
    }
}
